//$$
var $$ = Dom7;

//Loading flag
var loading = false;
var ajaxLoading = false;

// 初始化APP
var myApp = new Framework7({
    modalTitle: '云果',
    router: true,
    onAjaxStart: function (xhr) {
        ajaxLoading = true;
        myApp.showIndicator();
        setTimeout(function () {
            myApp.hideIndicator();
            //如果是超时则提示超时
            if (ajaxLoading == true) {

            }
        }, 5000);
    },
    onAjaxComplete: function (xhr) {
        ajaxLoading = false;
        myApp.hideIndicator();
    },
    cache: false,
    allowDuplicateUrls: true,
    preloadPreviousPage: false,
    //preloadPreviousPage: true,
    //pushState:true,
    imagesLazyLoadPlaceholder: "",
});

// 初始化视图
var mallView = myApp.addView('#mallView', {
    dynamicNavbar: true,
});
var starView = myApp.addView('#starView', {
    dynamicNavbar: true,
});
// var timeView = myApp.addView('#timeView', {
//     dynamicNavbar: true,
// });
var mineView = myApp.addView('#mineView', {
    dynamicNavbar: true,
});
var classifyView = myApp.addView('#classifyView', {
    dynamicNavbar: true,
});

// 视图切换
$$(document).on('click', '#footerBar .tab-link', function () {
    var that = $$(this);
    var view = that.attr('href').substring(1);
    switch (view) {
        case 'classifyView':
            classifyView.router.load({
                url: creatUrl('/yunsite/classify'),
                animatePages: false,
                reload: true,
            });
            break;
        case 'mineView':
            mineView.router.load({
                url: creatUrl('/yunucenter/index'),
                animatePages: false,
                reload: true,
            });
            break;
        // case 'timeView':
        //     timeView.router.load({
        //         url: creatUrl('/yunsite/speed_list'),
        //         animatePages: false,
        //         reload: true,
        //     });
        //
        //     break;
        case 'starView':
            starView.router.load({
                url: creatUrl('/yunsite/star'),
                animatePages: false,
                reload: true,
            });

            break;
        default:
            mallView.router.load({
                url: creatUrl('/yunsite/index'),
                animatePages: false,
                reload: true,
            });
            break;
    }
})


// 首页商品搜索
$$(document).on('search', '#ser', function () {

    var word = $$('.searchbar-new input').val();
    if(word == ''){
        myApp.alert('请输入正确的查询关键词');
        return false;
    }
    var href = $$('.link').attr('href');
    var url = href+'&word='+word;
    $$('.link').attr('href',url);
    $$('.link').trigger("click");

});

// 异步回调
function ajaxCallback(page, txt, reload) {
    if (!txt.match("^\{(.+:.+,*){1,}\}$")) { // html
        if (reload == 1) {
            page.view.router.reloadContent(txt);
        } else {
            page.view.router.loadContent(txt);
        }
    } else { // json
        var jData = jQuery.parseJSON(txt);
        if (jData.message) {
            myApp.alert(jData.message);
        }
        if (jData.callback) {
            eval(jData.callback);
        }
    }
}

// 表单异步回调
function formAjaxCallback(page, e) {
    // var xhr = e.detail.xhr;
    var txt = e.detail.data;
    ajaxCallback(page, txt, 1);
}

//倒计时类
var activeCountDown = function () {
    var _self = this;
    this.handle = {};
    this.timers = [];
    this.parent = {
        'second': 'minute',
        'minute': 'hour',
        'hour': ""
    };
    this.add = function (id) {
        _self.handle.id = setInterval(function () {
            _self.work(id, 'second');
        }, 1000);
        this.timers.push(_self.handle.id);
    };
    this.work = function (id, type) {
        if (type == "") {
            return false;
        }

        var e = document.getElementById("cd_" + type + "_" + id);
        var value = parseInt(e.innerHTML);
        if (value == 0 && _self.work(id, _self.parent[type]) == false) {
            clearInterval(_self.handle.id);
            return false;
        } else {
            e.innerHTML = (value == 0 ? 59 : (value - 1));
            return true;
        }
    };
    this.clear = function () {
        for (var i in this.timers) {
            clearInterval(this.timers[i]);
        }
        this.timers = [];
    };
};
//全局倒计时管理器
var gCountDownTimer = new activeCountDown();

//处理bar
function viewBarHandler(page) {
    var view = page.view;

    if ($$(view.activePage.container).hasClass('no-toolbar')) {
        myApp.hideToolbar('#footerBar');
    } else {
        myApp.showToolbar('#footerBar');
    }

    if ($$(view.activePage.container).hasClass('no-navbar')) {
        view.hideNavbar();
    } else {
        view.showNavbar();
    }
}

//所有页面动画加载前
$$(document).on('pageBeforeAnimation', function (e) {
    viewBarHandler(e.detail.page);
});
//加入购物车
$$(document).on('click', '.join', function () {

    
    var buyNums = parseInt($.trim($('#buyNums').val()))?parseInt($.trim($('#buyNums').val())):1;
   
    var id = $$(this).data('id');
    var type = 'goods';

    $.getJSON(creatUrl("yunsimple/joinCart"), {
        "goods_id": id,
        "goods_num": buyNums,
        'type': type,
        "random": Math.random
    }, function (content) {
        if (content.isError == false) {
            //获取购物车信息
            $.getJSON(creatUrl("simple/showCart"), {"random": Math.random}, function (json) {
                $('[name="mycart_count"]').text(json.count);
                $('[name="mycart_sum"]').text(json.sum);
                myApp.alert("目前选购商品共" + json.count + "件，合计：￥" + json.sum);
            });
        }
        else {
            myApp.alert(content.message);
        }
    });

})


//所有回退
$$(document).on('pageAfterBack', function (e) {
    viewBarHandler(e.detail.page);
});

//全局通用的上拉分页调用
function onInfinite(page) {
    if (loading) return;
    var container = page.container;
    loading = true;
    $$(container).find('.infinite-scroll-preloader').show();
    setTimeout(function () {
        loading = false;

        var view = page.view;

        var url = page.url;
        //下一页
        var currPage = $$(container).data('currpage');
        var maxPage = $$(container).data('maxpage');
        if (currPage >= maxPage) {
            myApp.addNotification({message: '没有数据了', hold: 2000});
            myApp.detachInfiniteScroll($$(container).find('.infinite-scroll'));
            $$(container).find('.infinite-scroll-preloader').remove();
            return;
        }
        var nextPage = parseInt(currPage) + 1;
        $$.ajax({
            url: url,
            data: {page: nextPage},
            type: 'GET',
            success: function (html) {
                $$(container).data('currpage', nextPage);
                // Append new items
                $$(container).find('.infinite-scroll-content').append(html);
                //callback
                page.onInfiniteCallback();
            },
        });

    }, 1000);
}

function reConfigWx(config) {
    if (typeof(wx) != 'undefined') {
        wx.onMenuShareTimeline(config);
        wx.onMenuShareAppMessage(config);
    }
}

// 页面初始化事件监听
$$(document).on('pageInit', function (e) {
        var page = e.detail.page;
        var container = page.container;

        gCountDownTimer.clear();

        //处理bar
        viewBarHandler(page);

        //分享处理
        share_title = $(container).find('input[name="share_title"]').val();
        share_desc = $(container).find('input[name="share_desc"]').val();
        share_link = $(container).find('input[name="share_link"]').val();
        share_imgUrl = $(container).find('input[name="share_imgUrl"]').val();
        if (!share_title) {
            share_title = '云果优品';
            share_desc = '找技术';
            share_link = 'http://v1.yunguostore.com';
            share_imgUrl = 'http://v1.yunguostore.com/favicon.ico';
        }
        reConfigWx({title: share_title, desc: share_desc, link: share_link, imgUrl: share_imgUrl});

        switch (page.name) {
            case 'mallIndex': // 首页
                $$(container).on('click', '#speed_list_link', function () {
                    myApp.showTab('#timeView');
                    timeView.router.load({
                        url: creatUrl('/yunsite/speed_list'),
                        animatePages: false,
                        reload: true,
                    });
                });
                break;
            case 'starIndex':

                break;
            case 'mallDetail': // 商品详情页            	
            	env = $$(container).find('input[name="env"]').val();
            	sys = $$(container).find('input[name="sys"]').val();
                $$(container).on('click', '.sharebut', function () {                    
                    var name = $$(container).find('input[name="share_title"]').val();
                    var link= $$(container).find('input[name="share_link"]').val();
                    var pic= $$(container).find('input[name="share_imgUrl"]').val();
                    var json = {name:name, link:link,pic:pic};
                    var data = JSON.stringify(json);

                   //console.log(data);
                    if (env == 'app') {
                        if (sys == 'ios') {
                            window.webkit.messageHandlers.shareToken.postMessage(data);
                        }
                        if (sys == 'android') {
                            window.android.share_token(data);
                        }
                    }
                })
                

                // 购买数量增减
                var store_nums = $$(container).find('[name="store_nums"]').val();
                $$(container).on('click', '.icon-minus', function () {
                    var nums = $$(container).find('[name="buyNums"]').val();
                    nums--;
                    nums = nums <= 1 ? 1 : nums;
                    $$(container).find('[name="buyNums"]').val(
                        nums);
                });

                $$(container).on('click', '.icon-add', function () {
                    var nums = $$(container).find('[name="buyNums"]').val();
                    nums++;
                    nums = nums >= store_nums ? store_nums : nums;
                    $$(container).find('[name="buyNums"]').val(
                        nums);
                });
                

               
                    // [立即购买],参考源于PC端products.js
                $$(container).on('click', '.buy', function () {
                    
                    var buyNums = $$(container).find('[name="buyNums"]').val(); // 数量
                    var id = $$(this).data('id'); // 商品ID
                    var type = 'goods'; // 购买类型
                    // 普通购买
                    var url = "/yunsimple/cart2/id/" + id + "/num/" + buyNums + "/type/" + type;
                    // 有促销活动（团购，抢购）
                    if ($$(this).data('promo') && $$(this).data('activeid')) {
                        url += "/promo/" + $$(this).data('promo') + "/active_id/" + $$(this).data('activeid');
                    }
                    $$.post(creatUrl(url), {}, function (ret) {
                        ajaxCallback(page, ret);
                    });
                });
                //限时抢购无购物车
                if ($$('.buy').data('promo') && $$('.buy').data('activeid')) {
                    $$('.join').hide();
                }

             


                if (document.getElementById('countdown')) {
                    gCountDownTimer.add('timeCount');
                }
                    //复制推广链接
                    var flag = $$(container).find('.subtoolbar').attr('data-flag');

                    if(flag==1) {

                        var clipboard = new Clipboard('#copy');
                        clipboard.on('success', function (e) {
                            myApp.alert("已复制");
                        });
                    }

                break;
            case 'login': // 登录启动页

                break;
            case 'loginForm': // 登录页
                var form = $$(container).find('form[name="login_form"]');
                $$(container).find('a.button-login').on('click', function (e) {
                    form.trigger('submit');
                });
                form.on('submitted', function (e) {
                    formAjaxCallback(page, e);
                });

                //微信授权登录
                $$(container).find('.button-weixin').on('click', function (e) {
                    var env = $$(container).find('input[name="env"]').val();
                    var sys = $$(container).find('input[name="sys"]').val();
                    var url = $$(container).find('input[name="url"]').val();
                    if (env == 'app') {
                        if (sys == 'ios') {
                            window.webkit.messageHandlers.weixinLogin.postMessage(url);
                        }
                        if (sys == 'android') {
                            window.android.weixin_login(url);
                        }
                    }
                });
                break;
            case 'loginActPage'://这个页面只有在APP下才会作为中间跳转
                var token = $$(container).find('input[name="token"]').val();
                var callback = $$(container).find('input[name="callback"]').val();
                if (env == 'app') {
                    if (sys == 'ios') {
                        window.webkit.messageHandlers.updateLocalToken.postMessage(token);
                    }
                    if (sys == 'android') {
                        window.android.updata_token(token);
                    }
                }
                page.view.router.reloadPage('/index.php?controller=yunucenter&action=index');
                break;
            case 'loginAppForm':

                break;
            case 'mallCart':
//减少商品数量
                $$(container).on('click', '.reduce', function () {
                    //库存超量检查
                    var obj = $$(this).attr('datajson');
                    var obj = eval('(' + obj + ')');
                    var countInput = $$('#count_' + obj.goods_id + '_' + obj.product_id);


                    if (parseInt(countInput.val()) - 1 <= 0) {
                        myApp.alert('购买的数量必须大于1件');
                    }
                    else {
                        countInput.val(parseInt(countInput.val()) - 1);
                        countInput.change();
                    }

                })

                //增加商品数量
                $$(container).on('click', '.add', function () {
                    //库存超量检查
                    var obj = $$(this).attr('datajson');
                    var obj = eval('(' + obj + ')');
                    var countInput = $$('#count_' + obj.goods_id + '_' + obj.product_id);
                    if (parseInt(countInput.val()) + 1 > parseInt(obj.store_nums)) {
                        myApp.alert('购买的数量大于此商品的库存量');
                    }
                    else {
                        countInput.val(parseInt(countInput.val()) + 1);
                        countInput.change();
                    }
                })
                //进行复杂的价格计算
                $$(container).on('change', '.tiny', function () {
                    var obj = $$(this).attr('datajson');
                    var obj = eval('(' + obj + ')');
                    var countInput = $$('#count_' + obj.goods_id + '_' + obj.product_id);
                    var countInputVal = parseInt(countInput.val());
                    var oldNum = countInput.data('oldNum') ? countInput.data('oldNum') : obj.count;

                    //商品数量大于1件
                    if (isNaN(countInputVal) || (countInputVal <= 0)) {
                        myApp.alert('购买的数量必须大于1件');
                        countInput.val(1);
                        countInput.change();
                    }
                    //商品数量小于库存量
                    else if (countInputVal > parseInt(obj.store_nums)) {
                        myApp.alert('购买的数量不能大于此商品的库存量');
                        countInput.val(parseInt(obj.store_nums));
                        countInput.change();
                    }
                    else {
                        var diff = parseInt(countInputVal) - parseInt(oldNum);
                        if (diff == 0) {
                            return;
                        }

                        var goods_id = obj.product_id > 0 ? obj.product_id : obj.goods_id;
                        var goods_type = obj.product_id > 0 ? "product" : "goods";

                        //更新购物车中此商品的数量
                        $.getJSON(creatUrl("yunsimple/joinCart"), {
                            "goods_id": goods_id,
                            "type": goods_type,
                            "goods_num": diff,
                            "random": Math.random()
                        }, function (content) {
                            if (content.isError == true) {
                                alert(content.message);
                                countInput.val(1);
                                countInput.change();
                            }
                            else {
                                var goodsId = [];
                                var productId = [];
                                var num = [];
                                $('[id^="count_"]').each(function (i) {
                                    var idValue = $(this).attr('id');
                                    var dataArray = idValue.split("_");

                                    goodsId.push(dataArray[1]);
                                    productId.push(dataArray[2]);
                                    num.push(this.value);
                                });
                                countInput.data('oldNum', countInputVal);
                                $.getJSON(creatUrl("/yunsimple/promotionRuleAjax"), {
                                    "goodsId": goodsId,
                                    "productId": productId,
                                    "num": num,
                                    "random": Math.random()
                                }, function (content) {
                                    if (content.promotion.length > 0) {
                                        $('#cart_prompt .indent').remove();

                                        for (var i = 0; i < content.promotion.length; i++) {
                                            $('#cart_prompt').append();
                                        }
                                        $('#cart_prompt').show();
                                    }
                                    else {
                                        $('#cart_prompt .indent').remove();
                                        $('#cart_prompt').hide();
                                    }

                                    /*开始更新数据*/
                                    $('#weight').html(content.weight);
                                    $('#origin_price').html(content.sum);
                                    $('#discount_price').html(content.reduce);
                                    $('#promotion_price').html(content.proReduce);
                                    $('#sum_price').html(content.final_sum);
                                    $('#sum_' + obj.goods_id + '_' + obj.product_id).html((obj.sell_price * countInputVal).toFixed(2));
                                });
                            }
                        });
                    }
                })
                //清空购物车
                $$(container).on('click', '.del', function () {
                    myApp.confirm('清空购物车吗？',
                        function () {
                            $$.post(creatUrl('/yunsimple/clearCart'), function (ret) {
                                ajaxCallback(page, ret);
                                myApp.alert('清空成功');
                            })
                        }


                )
        })
                //继续购买
                $$(container).on('click', '.btn_continue', function () {
                    window.location.reload();
                })
                //删除一种商品在购物车内
                $$(container).on('click', '.delone', function () {
                    //库存超量检查
                    var obj = $$(this).attr('datajson');
                    var obj = eval('(' + obj + ')');
                    var goods_id = obj.product_id > 0 ? obj.product_id : obj.goods_id;
                    var goods_type = obj.product_id > 0 ? "product" : "goods";
                    $.getJSON(creatUrl("yunsimple/removeCart"), {
                        "goods_id": goods_id,
                        "type": goods_type,
                        "random": Math.random()
                    }, function () {
                        page.view.router.reloadPage(creatUrl("yunsimple/cart"));
                    });
                })
                //结算
                $$(container).on('click', '.btn_pay', function () {
                    page.view.router.reloadPage(creatUrl("yunsimple/cart2"));
                })

                break;
            case
            'mallConfirm'
            : // 订单确认页
                $$(container).find('[name="order_form"]').on('submitted', function (e) {
                    formAjaxCallback(page, e);
                });
                break;
            case
            'mallPayment'
            :
                $$(container).find('a.button-pay').on('click', function (e) {
                    //$$(container).find('form[name="payForm"]').trigger('');

                });
                break;
            case
            'enrollForm'
            : // 注册页
                // 倒计时效果
            function countdown() {
                if (wait == 0) {
                    $$(container).find('.send').prop('disabled', false).html('重新发送');
                } else {
                    $$(container).find('.send').prop('disabled', true).html(
                        wait < 10 ? '0' + wait + '秒' : wait + '秒');
                    wait--;
                    timer = setTimeout(function () {
                        countdown()
                    }, 1000);
                }
            }

                // 发送验证码
                $$(container).on('click', '.send', function () {
                    var url = creatUrl('/yunsimple/_sendMobileCode');
                    var type = $(this).data('type');
                    if (type == "find_psd") {
                        var url = creatUrl('/yunsimple/send_message_mobile');
                    }
                    $$.ajax({

                        url: url,
                        type: 'post',
                        data: {
                            mobile: $$(
                                container).find('[name="mobile"]').val()
                        },
                        dataType: 'json',
                        success: function (ret) {
                            if (ret.isError) {
                                myApp.alert(ret.message);
                            } else {
                                myApp.addNotification({
                                    message: ret.message,
                                    hold: 2000
                                });
                                wait = 60;
                                var that = $$(this);
                                countdown();
                            }
                        },
                    });
                });

                //提交注册申请
                var form = $$(container).find('[name="reg_form"]');
                $$(container).find('a.button-enroll').on('click', function (e) {
                    form.trigger('submit');
                });
                form.on('submitted', function (e) {
                    formAjaxCallback(page, e);
                });
                break;
            case
            'find_password'
            :

                break;
            case
            'mineAlias'
            :
                $$(container).find('[name="alias_form"]').on('submitted', function (e) {
                    formAjaxCallback(page, e);
                });
                break;
            case
            'mineBirthday'
            :
                $$(container).find('[name="birthday_form"]').on('submitted', function (e) {
                    formAjaxCallback(page, e);
                });
                $('[name="birthday"]').mobiscroll().date({
                    theme: '',     // Specify theme like: theme: 'ios' or omit setting to use default
                    mode: 'scroller',       // Specify scroller mode like: mode: 'mixed' or omit setting to use default
                    display: 'modal', // Specify display mode like: display: 'bottom' or omit setting to use default
                    lang: 'zh',        // Specify language like: lang: 'pl' or omit setting to use default
                    minDate: new Date(1981, 0, 0, 0, 0),
                    maxDate: new Date(2021, 0, 0, 0, 0)
                });
                break;
            case
            'mineAdresList'
            :
                $$(container).on('click', '.area', function () {
                    var that = $$(this);
                    var id = that.attr('data');
                    // alert(id);
                    $$.post(creatUrl('/yunucenter/address_default'), {
                        id: id
                    }, function (ret) {
                        ajaxCallback(page, ret);
                    });
                });

                //点击地址后的按钮列表
                $$(container).find('.label-radio').on('click', function (e) {
                    var params = {
                        chk_addrid: $$(this).data('id')
                    };

                    var buttons = [{
                        text: '使用该地址',
                        onClick: function () {
                            $$.get(creatUrl('yunsimple/cart2selectAddress'), params, function (ret) {
                                ajaxCallback(page, ret);
                            });
                        }
                    }, {
                        text: '编辑',
                        onClick: function () {
                            page.view.router.loadPage(creatUrl('yunucenter/update_address/id/' + params.chk_addrid));
                        }
                    }, {
                        text: '删除',
                        onClick: function () {
                            $$.get(creatUrl('yunucenter/address_del'), params, function (ret) {
                                //ajaxCallback(page,ret);
                                //mineView.router.reloadPage(creatUrl('yunucenter/address'));
                                //page.view.router.reloadPage(creatUrl('yunucenter/address'));
                                ajaxCallback(page, ret);
                            });
                        }
                    }, {
                        text: '设置为默认地址',
                        onClick: function () {
                            $$.get(creatUrl('yunucenter/address_default'), params, function (ret) {
                                //mineView.router.reloadPage(creatUrl('yunucenter/address'));
                                ajaxCallback(page, ret);
                            });
                        }
                    }, {
                        text: '取消',
                        color: 'red',
                        onClick: function () {

                        }
                    },];
                    myApp.actions(buttons);
                });
                break;
            case
            'minesimpleTickt'
            :
                $$(container).find('.label-radio').on('click', function (e) {
                    var params = {
                        chk_ticketid: $$(this).data('id')
                    };

                    var buttons = [{
                        text: '使用',
                        onClick: function () {
                            $$.get(creatUrl('yunsimple/cart2selectTicket'), params, function (ret) {
                                ajaxCallback(page, ret);
                            });
                        }
                    },

                        {
                            text: '取消',
                            color: 'red',
                            onClick: function () {

                            }
                        },
                    ];
                    myApp.actions(buttons);
                });
                break;
            case
            'mineCoupon'
            :
                $$(container).find('[name="exchange_form"]').on('submitted', function (e) {
                    formAjaxCallback(page, e);
                });
                break;
            case
            'minePassword'
            :
                $$(container).find('[name="password_form"]').on('submitted', function (e) {
                    formAjaxCallback(page, e);
                });
                break;
            case
            'mineNewAdres'
            :
                $$(container).on('change', '.prov', function () {
                    var that = $$(this);
                    var area_id = that.val();
                    $$.post(creatUrl('/yunucenter/get_citys'), {
                        province_id: area_id
                    }, function (ret) {
                        var json = eval('(' + ret + ')');
                        console.log(json);
                        if (!json.isError) {
                            var str = '<option value="">请选择城市</option>';
                            var data = json.data;
                            for (var i = 0; i < data.length; i++) {
                                str += '<option value="' + data[i].area_id + '">' + data[i].area_name + '</option>'
                            }
                            $$(container).find('[name="city"]').html(str);
                        } else {
                            alert('没有查询到相关的城市');
                        }
                    });
                });
                $$(container).on('change', '.city', function () {
                    var that = $$(this);
                    var city_id = that.val();
                    $$.post(creatUrl('/yunucenter/get_areas'), {
                        city_id: city_id
                    }, function (ret) {
                        var json = eval('(' + ret + ')');
                        console.log(json);
                        if (!json.isError) {
                            var str = '<option value="">请选择区域</option>';
                            var data = json.data;
                            for (var i = 0; i < data.length; i++) {
                                str += '<option value="' + data[i].area_id + '">' + data[i].area_name + '</option>'
                            }
                            $$(container).find('[name="area"]').html(str);
                        } else {
                            alert('没有查询到相关的城市');
                        }
                    });
                });
                $$(container).find('[name="addAdres_form"]').on('submitted', function (e) {
                    //formAjaxCallback(page, e);
                    var ret = jQuery.parseJSON(e.detail.data);
                    if (ret.isError == 0) {
                        page.view.router.back({
                            url: creatUrl('yunucenter/address'),
                            force: true
                        });
                    }
                    if (ret.message) {
                        myApp.alert(ret.message);
                    }
                });
                break;
            case
            'mineEditAdres'
            :
                var city_id = $$(container).find('[name="city_1"]').val();
                var area_id = $$(container).find('[name="area_1"]').val();
                $$(container).on('change', '.prov', function () {
                    var that = $$(this);
                    var area_id = that.val();
                    $$.post(creatUrl('/yunucenter/get_citys'), {
                        province_id: area_id
                    }, function (ret) {
                        var json = eval('(' + ret + ')');
                        console.log(json);
                        if (!json.isError) {
                            var str = '<option value="">请选择城市</option>';
                            var data = json.data;
                            for (var i = 0; i < data.length; i++) {
                                if (city_id == data[i].area_id) {
                                    str += '<option value="' + data[i].area_id + '" selected="selected">' + data[i].area_name + '</option>'
                                } else {
                                    str += '<option value="' + data[i].area_id + '">' + data[i].area_name + '</option>'
                                }
                            }
                            $$(container).find('[name="city"]').html(str);
                        } else {
                            alert('没有查询到相关的城市');
                        }
                    });
                });
                $$(container).on('change', '.city', function () {
                    var that = $$(this);
                    var c_id = city_id;

                    $$.post(creatUrl('/yunucenter/get_areas'), {
                        city_id: city_id
                    }, function (ret) {
                        var json = eval('(' + ret + ')');
                        console.log(json);
                        if (!json.isError) {
                            var str = '<option value="">请选择区域</option>';
                            var data = json.data;
                            for (var i = 0; i < data.length; i++) {
                                if (area_id == data[i].area_id) {
                                    str += '<option value="' + data[i].area_id + '" selected="selected">' + data[i].area_name + '</option>'
                                } else {
                                    str += '<option value="' + data[i].area_id + '">' + data[i].area_name + '</option>'
                                }
                            }
                            $$(container).find('[name="area"]').html(str);
                        } else {
                            alert('没有查询到相关的城市');
                        }
                    });
                });
                $$(container).find('[name="province"]').change();
                $$(container).find('[name="city"]').change();
                $$(container).find('[name="editAdres_form"]').on('submitted', function (e) {
                    //formAjaxCallback(page, e);
                    var ret = jQuery.parseJSON(e.detail.data);
                    if (ret.isError == 0) {
                        page.view.router.back({
                            url: creatUrl('yunucenter/address'),
                            force: true
                        });
                    }
                    if (ret.message) {
                        myApp.alert(ret.message);
                    }
                });
                break;
            case
            'mineTenants'
            :
                $$(container).find('[name="tenants_form"]').on('submitted', function (e) {
                    formAjaxCallback(page, e);
                });
                break;
            case
            'mineWithdraw'
            :
                $$(container).find('[name="withdraw_form"]').on('submitted', function (e) {
                   
                     formAjaxCallback(page, e);
                     
                });
                break;
            case
            'mineaccountdetail'
            :

                break;
            case
            'mineaccount'
            :

                break;
            case
            'minewithdrawdetail'
            :

                break;
            case
            'mineCustomization'
            :
                $$(container).on('click', '.type1', function () {
                    var that = $$(this);
                    $$(container).find('.type2').removeClass('active');
                    that.addClass('active');
                    $$(container).find('[name="name"]').val('');
                    $$(container).find('[name="mobile"]').val('');
                    $$(container).find('[name="content"]').val('');
                    $$(container).find('[name="type"]').val(1);
                });
                $$(container).on('click', '.type2', function () {
                    var that = $$(this);
                    $$(container).find('.type1').removeClass('active');
                    that.addClass('active');
                    $$(container).find('[name="name"]').val('');
                    $$(container).find('[name="mobile"]').val('');
                    $$(container).find('[name="content"]').val('');
                    $$(container).find('[name="type"]').val(2);
                });
                $$(container).find('[name="custom_form"]').on('submitted', function (e) {
                    formAjaxCallback(page, e);
                });
                break;
            case
            'mineOrders'
            :

                break;
            case
            'mallPreSell'
            :

                break;
            case
            'mallSearch'
            :
                $$(".sub_btn").click(function () {
                    var word = $("input[name='word']").val();
                    var url = $(this).find('a').attr('href');
                    url = url.replace('xxxx', word);
                    $(this).find('a').attr('href', url);
                });

                break;
            case
            'mineAccount'
            :
                // $$(container).on('click', '.choose-avatar',
                // 	function() {
                // 		var that = $$(this);
                // 		var buttons1 = [{
                // 			text: '现场拍摄',
                // 			onClick: function() {
                // 				//调用摄像头事件
                // 				myApp.alert('', '调用摄像头事件');
                // 			}
                // 		}];
                // 		var buttons2 = [{
                // 			text: '本地相册',
                // 			onClick: function() {
                // 				//调用本地相册事件
                // 				myApp.alert('', '调用本地相册事件');
                // 			}
                // 		}];
                // 		var groups = [buttons1, buttons2];
                // 		myApp.actions(groups);
                // 	})
                $$(container).on('change', '.attach',
                    function () {
                        var that = $$(this);
                        ajaxFileUpload(page, 'attach', creatUrl('/yunucenter/user_ico_upload'), 1, that);
                    });

                $$(container).on('click', '.choose-sex',
                    function () {
                        var that = $$(this);
                        var sex = $$(container).find('.sex');
                        var buttons1 = [{
                            text: '男',
                            onClick: function () {
                                $$.post(creatUrl('/yunucenter/info_edit_act'), {
                                    sex: 1
                                }, function (ret) {
                                    ajaxCallback(page, ret);
                                });
                                sex.val("男")
                            }
                        }];
                        var buttons2 = [{
                            text: '女',
                            onClick: function () {
                                $$.post(creatUrl('/yunucenter/info_edit_act'), {
                                    sex: 2
                                }, function (ret) {
                                    ajaxCallback(page, ret);
                                });
                                sex.val("女")
                            }
                        }];
                        var groups = [buttons1, buttons2];
                        myApp.actions(groups);
                    })


                break;

            case
            'mineClaim'
            :
                $$(container).on('change', '.file1',
                    function () {
                        ajaxFileUpload1('file1', creatUrl('/yunucenter/upload_pic'), 'img_file1', container);
                    });
                $$(container).on('change', '.file2',
                    function () {
                        ajaxFileUpload1('file2', creatUrl('/yunucenter/upload_pic'), 'img_file2', container);
                    });
                $$(container).on('change', '.file3',
                    function () {
                        ajaxFileUpload1('file3', creatUrl('/yunucenter/upload_pic'), 'img_file3', container);
                    });
                $$(container).on('click', '.delete',
                    function () {
                        var that = $$(this);
                        $$(container).find('.img_' + that.attr('data')).html('');
                    });
                $$(container).find('[name="refunds_form"]').on('submitted', function (e) {
                    formAjaxCallback(page, e);
                });
                break;

            case
            'mineCancelService'
            :
                $$(container).on('click', '.cancel',
                    function () {
                        var that = $$(this);
                        $$.post(creatUrl('/yunucenter/refunds_del'), {
                            id: that.attr('data')
                        }, function (ret) {
                            console.log(ret);
                            ajaxCallback(page, ret);
                        });
                    });
                break;
            case
            'minefeedback'
            :
                $$(container).on('change', '.file1',
                    function () {
                        ajaxFileUpload1('file1', creatUrl('/yunucenter/upload_pic'), 'img_file1', container);
                        +
                            $$(container).find('.up_file1').hide();
                    });
                $$(container).on('change', '.file2',
                    function () {
                        ajaxFileUpload1('file2', creatUrl('/yunucenter/upload_pic'), 'img_file2', container);
                        $$(container).find('.up_file2').hide();
                    });
                $$(container).on('change', '.file3',
                    function () {
                        ajaxFileUpload1('file3', creatUrl('/yunucenter/upload_pic'), 'img_file3', container);
                        $$(container).find('.up_file3').hide();
                    });
                $$(container).find('[name="back_form"]').on('submitted', function (e) {
                    formAjaxCallback(page, e);
                });
                break;
            case
            'timeIndex'
            :
                //倒计时
                page.onInfiniteCallback = function () {
                    //初始化倒计时
                    $$(container).find('.alink').each(function () {
                        if ($$(this).data('isTimer') != 1) {
                            var id = $(this).attr('cutid');
                            gCountDownTimer.add(id);
                            $$(this).data('isTimer', 1);
                        }
                    });
                }
                page.onInfiniteCallback();
                break;
            case
            'minePay'
            :
                $$(container).on('click', '.cancel_order',
                    function () {
                        var that = $$(this);
                        myApp.confirm('确认要取消订单吗？',
                            function () {
                                $$.get(creatUrl('/yunucenter/order_status'), {
                                    op: 'cancel',
                                    order_id: that.attr('data')
                                }, function (ret) {
                                    ajaxCallback(page, ret, 1);
                                    page.view.router.refreshPreviousPage();
                                });
                                return false;
                            },
                            function () {
                                //myApp.alert('You clicked Cancel button');
                            }
                        );
                    });
                $$(container).on('click', '.confirm_order',
                    function () {
                        var that = $$(this);
                        myApp.confirm('确认要执行此操作吗？',
                            function () {
                                $$.get(creatUrl('/yunucenter/order_status'), {
                                    op: 'confirm',
                                    order_id: that.attr('data')
                                }, function (ret) {
                                    ajaxCallback(page, ret, 1);
                                    page.view.router.refreshPreviousPage();
                                });
                                return false;
                            },
                            function () {
                                //myApp.alert('You clicked Cancel button');
                            }
                        );
                    });

                //付款选择
                $$(container).find('.button.pay').on('click', function () {
                    var href = $(this).data('href');
                    var buttons = [
                        {
                            text: '请选择支付方式',
                            label: true
                        },
                        {
                            text: '支付宝支付',
                            bold: true,
                            onClick: function () {
                                window.location.href = href + '&payment_id=16';
                            }
                        }, /*
                         {
                         text: '微信支付',
                         bold: true,
                         onClick: function () {
                         window.location.href = href+'&payment_id=8';
                         }
                         },*/
                        {
                            text: '取消',
                            color: 'red',
                            onClick: function () {

                            }
                        },
                    ];
                    myApp.actions(buttons);
                });
                break;
            case
            'logout'
            :
                if (myApp.device.webView) {
                    if (myApp.device.os == 'ios') {
                        window.webkit.messageHandlers.updateLocalToken.postMessage('');
                    } else {
                        window.android.updata_token('');
                    }
                }
                myApp.showTab('#mallView');
                mallView.router.reloadPage(creatUrl('/yunsite/index'));
                break;
            default:
                console.dir('data-page=' + e.detail.page.name + ' inited');
                break;
        }

        //监听所有的下拉刷新
        var pullToRefreshContent = $$(container).find('.pull-to-refresh-content');
        pullToRefreshContent.on('pullstart', function () {
            $$(page.view.pagesContainer).find('.page-on-left').hide();
        });
        pullToRefreshContent.on('refresh', function () {
            setTimeout(function () {
                page.view.refreshPage();
            }, 500);
        });
        $$(page.view.pagesContainer).find('.page-on-left').show();

        //监听所有的上拉分页
        $$(container).on('infinite', '.infinite-scroll', function () {
            onInfinite(page);
        });

        //在线客服
        $(container).find('.service').on('click', function () {
            _MEIQIA('showPanel');
        });

        //
        //closeInitMask();
    }
);

/**
 * 头像编辑 图片上传
 */
function ajaxFileUpload(page, upload, url, is_head, that) {
    $.ajaxFileUpload({
        url: url, //需要链接到服务器地址
        secureuri: false,
        fileElementId: upload, //文件选择框的id属性
        dataType: 'text', //服务器返回的格式
        success: function (data, status) //相当于java中try语句块的用法
        {
            data = data.replace('<audio controls="controls" style="display: none;"></audio>', '');
            //$('#__content__').html(data);
            var json = eval('(' + data + ')');
            console.log(json);
            if (!json.isError) {
                if (is_head) {
                    page.view.router.reloadPage(creatUrl('yunucenter/index'));
                }
            }
        },
        error: function (data, status, e) //相当于java中catch语句块的用法
        {
            //$('#__content__').html('添加失败');
        }
    });
}

/**
 * 图片上传
 */
function ajaxFileUpload1(upload, url, class_name, container) {
    $.ajaxFileUpload({
        url: url, //需要链接到服务器地址
        secureuri: false,
        fileElementId: upload, //文件选择框的id属性
        dataType: 'text', //服务器返回的格式
        success: function (data, status) //相当于java中try语句块的用法
        {
            data = data.replace('<audio controls="controls" style="display: none;"></audio>', '');
            //$('#__content__').html(data);
            var json = eval('(' + data + ')');
            console.log(json);
            if (!json.isError) {
                // <div class="addon">
                //         <a href="javascript:void(0)" class="delete"><i class="icon icon-delete"></i></a>
                //         <img src="tmp/11.jpg" alt="">
                //         </div>
                var str = '';
                str += '<a href="javascript:void(0)" class="delete" data="' + upload + '"><i class="icon icon-delete"></i></a>';
                str += '<img style="height: 100%;" src="' + json.data + '" alt="">';
                str += '<input type="hidden" name="imgs[' + upload + ']" value="' + json.data + '">';
                $$(container).find('.' + class_name).html(str);
            }
        },
        error: function (data, status, e) //相当于java中catch语句块的用法
        {
            //$('#__content__').html('添加失败');
        }
    });
}